package com.ssm.juc.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

public class OddEven {
    int len;
    int[] num;
    int idx;
    final Boolean lock = false;
    ReentrantLock rlock = new ReentrantLock();
    CountDownLatch latch;

    public OddEven(int len) {
        this.len = len;
        num = new int[len];
        for (int i = 0; i < len; i++) {
            num[i] = i;
        }
        idx = 0;
    }

    class Odd implements Runnable {
        @Override
        public void run() {
            while (idx < len) {
                synchronized (lock) {
                    if (idx < len && (num[idx] >> 1 << 1) != num[idx]) {
                        System.out.print(num[idx]);
                        System.out.println("--Odd");
                        ++idx;
                    }
                }


//                rlock.lock();
//                if (idx < len && (num[idx] >> 1 << 1) != num[idx]){
//                    System.out.print(num[idx]);
//                    System.out.println("--Odd");
//                    ++idx;
//                }
//                rlock.unlock();

            }

            latch.countDown();
        }
    }

    class Even implements Runnable {
        @Override
        public void run() {
            while (idx < len) {
                synchronized (lock) {
                    if (idx < len && (num[idx] >> 1 << 1) == num[idx]) {
                        System.out.print(num[idx]);
                        System.out.println("--Even");
                        ++idx;
                    }
                }

//                rlock.lock();
//                if (idx < len && (num[idx] >> 1 << 1) == num[idx]){
//                    System.out.print(num[idx]);
//                    System.out.println("--Even");
//                    ++idx;
//                }
//                rlock.unlock();
            }

            latch.countDown();
        }
    }

    public void execute(int threadNum) {
        latch = new CountDownLatch(threadNum);

        long begin = System.currentTimeMillis();

        Thread odd = new Thread(new Odd());
        Thread even = new Thread(new Even());
        odd.start();
        even.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("total time:" + (end - begin));
    }

    public static void main(String[] args) {
        OddEven oe = new OddEven(100000);
        oe.execute(2);
    }
}
